package cn.cq.admin.service.impl;

import cn.cq.common.BaseUtils;
import cn.cq.admin.service.SystemService;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.captcha.generator.MathGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;

/**
 * cn.cq.admin.service.impl
 *
 * @author  dicraft
 */
@Slf4j
@Service
public class SystemServiceImpl implements SystemService {

    @Value("${app.code.timeout}")
    private String timeOut;

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public SaResult createShearCaptcha(HttpServletResponse response) {
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 45, 4, 4);
        // 自定义验证码内容为四则运算方式
        captcha.setGenerator(new MathGenerator());
        // 重新生成code
        captcha.createCode();
        try {
            OutputStream out = response.getOutputStream();
            captcha.write(out);
            out.close();
        } catch (IOException e) {
            log.error(BaseUtils.getStackTrace(e));
        }
        return SaResult.ok();
    }

    @Override
    public SaResult createCircleCaptcha(HttpServletResponse response,String key) {
        //定义图形验证码的长、宽、验证码字符数、干扰元素个数
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        try {
            OutputStream out = response.getOutputStream();
            captcha.write(out);
            String code = captcha.getCode();
            redisTemplate.opsForValue().set(key,code,Integer.parseInt(timeOut), TimeUnit.SECONDS);
            out.close();
        } catch (IOException e) {
            log.error(BaseUtils.getStackTrace(e));
        }
        return SaResult.ok();
    }
}
